package com.ricchieri.manage.bean;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;

import com.ricchieri.common.BusinessSettings;
import com.ricchieri.util.FacesUtil;
import com.ricchieri.util.StringUtils;

public abstract class GenericManageBean implements Serializable {

	private static final long serialVersionUID = 6365726930107620968L;
	
	
	public String obtainDescription(String property) {
		if(StringUtils.isEmpty(property)) {
			return "";
		}
		
		return FacesUtil.getMessage(property);
	}
	
	public String obtainBooleanDescription(Boolean property) {
		if (property) {
			return FacesUtil.getMessage("yes");
		} else {
			return FacesUtil.getMessage("no");
		}
	}
	
	@PostConstruct
	public void initializeSession() {	    
		FacesContext context = FacesContext.getCurrentInstance();
		context.getExternalContext().getSession(true);
	}
	
	public String getErrorMessage(String clientId) {
		FacesContext fc = FacesContext.getCurrentInstance();
		Iterator<FacesMessage> iter = fc.getMessages(clientId);
		if (iter.hasNext()) {
			return iter.next().getDetail();
		}
		return "";
	}
	
	public String formatDate(Date date) {
		SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
		
		if(date != null) {
			return format.format(date);
		}
		return "";
	}
	
	public String formatTime(Date date) {
		SimpleDateFormat format = new SimpleDateFormat("kk:mm:ss");
		
		if(date != null) {
			return format.format(date);
		}
		return "";
	}
	
	public String formatDateTime(Date date) {
		SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy kk:mm");
		
		if(date != null) {
			return format.format(date);
		}
		return "";
	}

	public String formatNumberWithoutDecimals(Double number) {
		return String.valueOf(Math.round(number.doubleValue()));
	}
	
	public <T, S> List<Map.Entry<T, S>> mapToList(Map<T, S> map) {
	    if (map == null) {
	        return null;
	    }

	    List<Map.Entry<T, S>> list = new ArrayList<Map.Entry<T, S>>();
	    list.addAll(map.entrySet());

	    return list;
	}
	
	public String replaceBreaklines(String string) {
		return string.replaceAll("\n", "<br/>");
	}
	
	public int pageSize() {
		return BusinessSettings.ROW_MAX_RESULT;
	}
}
